import { z } from 'zod'
import type { Request } from 'express'
import { tagService } from '@server/services/tag-service'
import { ApiResponse } from '@data/api'
import { NotFoundError, ParameterError } from '@server/error/errors'

// 导出参数验证 schema
export const bodySchema = z.object({
  name: z.string().optional(),
  color: z.string().optional(),
})

export default async function updateTag(request: Request, data: z.infer<typeof bodySchema>) {
  const id = request.params.id

  try {
    const tag = await tagService.updateTag(id, data)

    if (!tag) {
      throw new NotFoundError('Tag not found')
    }

    const response: ApiResponse = {
      success: true,
      data: tag,
      message: 'Tag updated successfully',
    }

    return response
  } catch (error) {
    if (error instanceof NotFoundError) {
      throw error
    }
    throw new ParameterError(error instanceof Error ? error.message : 'Failed to update tag')
  }
}
